<!--
 * @Description: 单位管理页面
-->
<template>
  <BaseMainSlot :show-tab="true">
    <template v-slot:btn-box>
      <ActionBar
        :page-no="64"
        :add-active="addActive"
        :del-active="delActive"
        :has-edit="false"
        :has-save="false"
        :has-cancel="false"
        @add="add"
        @del="del"
      />
    </template>
    <template v-slot:tab-select>
      <SelectButton
        :buttonselectlist="buttonselectlist"
        @nowselectbuttonindex="batchstaumet"
      />
    </template>
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"></SearchForm>
    </template>
    <template v-slot:table-box>
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        height="92%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column prop="inventoryTaskName" label="任务名称" />
        <el-table-column prop="warehouseName" label="盘点仓库" />
        <el-table-column label="查看产品">
          <template v-if="scope.row.inventoryTaskNo" slot-scope="scope">
            <el-button
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="checkProduct(scope.row)"
            >
              <i class="el-icon-view"></i> 查看产品
            </el-button>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="product" label="盘点产品" /> -->
        <el-table-column prop="personName" label="盘点人" />
        <el-table-column prop="executionDate" label="执行日期" />
        <el-table-column v-if="curTabIndex != 0" prop="auditTime" label="审核日期" />
        <!-- <el-table-column v-if="curTabIndex == 0" width="140" label="操作">
          <template v-if="scope.row.inventoryTaskNo" slot-scope="scope">
            <el-button v-if="judgePermission(64, 'edit')" class="text-btn-cursor" type="text" size="small" @click="handleDelete(scope.row)"><i class="el-icon-check"></i> 通过</el-button>
            <el-button v-if="judgePermission(64, 'delete')" class="text-btn-cursor cursor-delete" type="text" size="small" @click="handleEdit(scope.row)"><i class="el-icon-close"></i> 不通过</el-button>
          </template>
        </el-table-column>-->
        <el-table-column v-if="curTabIndex == 2" label="查看">
          <template v-if="scope.row.inventoryTaskNo" slot-scope="scope">
            <el-popover
              placement="top-start"
              title="拒绝原因"
              width="200"
              trigger="hover"
              :content="scope.row.reason"
            >
              <el-button
                slot="reference"
                class="text-btn-cursor"
                type="text"
                size="small"
              >查看原因</el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="dialogTitle + '任务信息'"
        :visible.sync="dialogFormVisible"
        :before-close="cancel"
        width="40%"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item label="任务名称:" prop="inventoryTaskName" class="w50p">
            <el-input v-model="formData.inventoryTaskName" clearable />
          </el-form-item>
          <el-form-item label="盘点仓库:" prop="warehouseNo" class="w50p">
            <el-select
              v-model="formData.warehouseNo"
              clearable
              filterable
              @change="getCurrentMaterialValue"
            >
              <el-option
                v-for="item in warehouseList"
                :key="item.warehouseNo"
                :label="item.warehouseName"
                :value="item.warehouseNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="盘点人:" class="w100p" prop="personNo">
            <el-form-item
              class="w100p"
              style="width: calc(33% - 20px) !important; padding-left: 0 !important"
              prop="purchasingDepartmentNo"
            >
              <el-select
                v-model="formData.purchasingDepartmentNo"
                clearable
                @change="getPostList"
              >
                <el-option
                  v-for="(item, index) in departmentList"
                  :key="index.departmentNo"
                  :label="item.departmentName"
                  :value="item.departmentNo"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              class="w100p"
              style="width: calc(33% - 20px) !important; padding-left: 0 !important; margin-left: 30px"
              prop="postNo"
            >
              <el-select
                v-model="formData.postNo"
                clearable
                @change="getStaffList"
              >
                <el-option
                  v-for="(item, index) in postList"
                  :key="index.postNo"
                  :label="item.postName"
                  :value="item.postNo"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              class="w100p"
              style="width: calc(33% - 20px) !important; padding-left: 0 !important; margin-left: 30px"
              prop="personNo"
            >
              <el-select v-model="formData.personNo" clearable>
                <el-option
                  v-for="(item, index) in staffList"
                  :key="index.personNo"
                  :label="item.person.name"
                  :value="item.personNo"
                />
              </el-select>
            </el-form-item>
          </el-form-item>
          <el-form-item label="执行日期:" prop="executionDate" class="w50p">
            <el-date-picker
              v-model="formData.executionDate"
              align="right"
              type="date"
              placeholder="选择日期"
            />
          </el-form-item>
          <el-form-item label="盘点产品:" prop="product" class="w100p">
            <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
            >全选</el-checkbox>
            <div style="margin: 0 10px;"></div>
            <el-checkbox-group
              v-model="checkedNos"
              @change="handlecheckedNosChange"
            >
              <el-checkbox
                v-for="product in productList"
                :key="product.goodsNo"
                :label="product.goodsName"
              >{{ product.goodsName }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >保 存</el-button>
        </div>
      </el-dialog>

      <el-dialog
        :title="'产品详情'"
        :visible.sync="dialogProductFormVisible"
        width="40%"
      >
        <div class="product-detail">
          <div class="title">产品列表：</div>
          <div class="product-list">
            <div
              v-for="(item, index) in curProductList"
              :key="index"
              class="product-item"
            >{{ item.goodsName }}</div>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="closeProduct()">关 闭</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import SearchForm from '@/components/searchForm';
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import nowpagereq from "@/api/digital-operation/warehouse-check";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
import SelectButton from "@/components/selectbutton/index.vue";
import { mymixin } from "@/utils/mixin";
import warehouseManage from "@/api/basic-info-manage/warehouse-manage";
import staffManage from "@/api/digital-operation/personnel-cost-mansge/staff-manage/index";

import managementtwo from "@/api/digital-production/agr-input-management/agr-input-managementtwo";
import { mapGetters } from "vuex";
export default {
  // eslint-disable-next-line vue/name-property-casing
  name: "check-task-create",
  components: { SearchForm, ActionBar, Pagination, BaseMainSlot, SelectButton },
  mixins: [mymixin],
  data() {
    return {
      formConfig: [
        {
          label: '任务名称',
          prop: 'inventoryTaskName',
          type: 'input',
        }, {
          label: '盘点仓库',
          prop: 'warehouseNo',
          type: 'select',
          options: [], // warehouseList
          optionKey: { label: 'warehouseName', value: 'warehouseNo' },
        }, {
          label: '盘点人',
          prop: 'personNo',
          type: 'select',
          options: [], // personList
          optionKey: { label: 'personName', value: 'personNo' },
        }, {
          label: '执行日期',
          prop: 'executionDate',
          type: 'date',
        }, 
      ],
      searchlist: {},
      unitList: [],
      dialogTitle: "",
      dialogFormVisible: false,
      buttonselectlist: [
        { name: "未审核" },
        { name: "审核通过" },
        { name: "审核未通过" }
      ],
      curTabIndex: 0,
      warehouseList: [],
      productList: [],
      personList: [],
      isIndeterminate: false,
      checkedNos: [],
      checkAll: true,

      rules: {
        inventoryTaskName: [
          { required: true, message: "请输入任务名称", trigger: "change" }
        ]
      },

      dialogProductFormVisible: false,
      curProductList: [],
      // 部门岗位员工列表
      departmentList: [],
      postList: [],
      staffList: []
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {},
  created() {
    // 获取表格数据
    this.getTableDataList();
    this.getWarehouseList();
    this.getDepartmentList();
    this.getPersonList();
  },
  mounted() {},
  methods: {
    // 获取部门列表
    getDepartmentList() {
      managementtwo.getDepartmentList().then(res => {
        // eslint-disable-next-line eqeqeq
        if (res.code != 1) {
          return;
        }
        this.departmentList = res.data;
      });
    },
    getPostList(no) {
      managementtwo.getPostList(no).then(res => {
        // eslint-disable-next-line eqeqeq
        if (res.code != 1) {
          return;
        }
        this.postList = res.data;
      });
    },
    getPersonList() {
      // let params = { entity: {} };
      staffManage.getStaffListByCondition().then(res => {
        this.personList = res.data;
        let list = res.data.map(el => {
          return { ...el, personName: el.person.name }
        })
        this.setOptions(this.formConfig, 'personNo', list)
      });
    },
    getStaffList(no) {
      managementtwo.getEmployeeList(no).then(res => {
        // eslint-disable-next-line eqeqeq
        if (res.code != 1) {
          return;
        }
        this.staffList = res.data;
      });
    },
    // 多选框选择方法
    handleCheckAllChange(val) {
      console.log(val);
      if (val) {
        this.checkedNos = this.productList.map(item => {
          return item.goodsName;
        });
      } else {
        this.checkedNos = [];
      }
      this.isIndeterminate = false;
    },
    handlecheckedNosChange(value) {
      console.log(value, this.checkedNos, "checkedNos");
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.productList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.productList.length;
    },
    batchstaumet(index) {
      this.curTabIndex = index;
      this.getTableDataList();
    },
    getCurrentMaterialValue(no) {
      nowpagereq.getCurrentMaterialValue({ warehouseNo: no }).then(res => {
        this.productList = res.data;
      });
    },
    getWarehouseList() {
      let params = { entity: {} };
      warehouseManage.getWareHouseListByCondition(params).then(res => {
        this.warehouseList = res.data;
        this.setOptions(this.formConfig, 'warehouseNo', res.data)
      });
    },
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          auditStatus: this.curTabIndex,
          ...this.searchlist
        }
      };
      nowpagereq.queryPageByCondition(params).then(res => {
        this.loading = false;
        if (res.code === 0) {
          this.$message.error("查询失败");
        }
        let data = res.data;
        // 赋值总条数
        this.totalSize = data.totalElements;
        // 赋值数组
        this.tableData = data.content;
        this.addblankmet();
        this.resetActionBar();
      });
      // }
    },
    checkProduct(row) {
      if (row.inventoryTaskNo) {
        this.dialogProductFormVisible = true;
        nowpagereq
          .queryAllByInventoryTaskNo(row.inventoryTaskNo)
          .then(result => {
            this.curProductList = result.data;
          });
      }
    },
    closeProduct() {
      this.curProductList = [];
      this.dialogProductFormVisible = false;
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    async handleEdit(row) {
      if (row.inventoryTaskNo) {
        this.openDialog("edit");
        this.formData = JSON.parse(JSON.stringify(row));
        nowpagereq
          .getCurrentMaterialValue({ warehouseNo: this.formData.warehouseNo })
          .then(res => {
            this.productList = res.data;
            nowpagereq
              .queryAllByInventoryTaskNo(this.formData.inventoryTaskNo)
              .then(result => {
                this.checkedNos = result.data.map(item => {
                  return item.goodsName;
                });
              });
          });
      }
    },
    resetState() {
      this.isIndeterminate = false;
      this.checkedNos = [];
      this.checkAll = true;
      this.productList = [];
    },
    // 添加
    add() {
      this.openDialog("add");
      this.formData = {};
    },
    // 取消
    cancel() {
      this.closeDialog();
      this.resetState();
      this.formData = {};
    },
    // 初始化操作栏状态
    resetActionBar() {
      this.nowChanceStau = "";
      this.formData = {};
    },
    handleSelectionChange(list) {
      this.selectedPlantingUnitList = [];
      // eslint-disable-next-line no-unused-vars
      let notvalue = true;
      this.selectedPlantingUnitList = list.map(item => {
        if (item.unitNo) {
          return item.unitNo;
        } else {
          notvalue = false;
          return "";
        }
      });
    },
    delmessage() {
      nowpagereq
        .delPlantingUnitById(this.selectedPlantingUnitList)
        .then(res => {
          if (res.code === 1) {
            this.$message.success("删除成功");
            this.getTableDataList();
          } else {
            this.$message.error("删除失败");
          }
        });
    },
    handleDelete(data) {
      // nowpagereq.delPlantingUnitById([data.unitNo]).then(res => {
      //   if (res.code === 1) {
      //     this.$message.success('删除成功')
      //     this.getTableDataList();
      //   } else {
      //     this.$message.error('删除失败')
      //   }
      // })
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          nowpagereq.delPlantingUnitById([data.unitNo]).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.getTableDataList();
            } else {
              this.$message.warning(res.msg || "删除失败");
            }
          });
        })
        .catch(() => {
          this.$message("取消删除");
        });
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            let params = JSON.parse(JSON.stringify(this.formData));
            let taskGoodsMapperList = [];
            this.checkedNos.forEach(el => {
              let item = this.productList.find(obj => obj.goodsName === el);
              if (item) {
                taskGoodsMapperList.push({
                  goodsName: item.goodsName,
                  goodsNo: item.goodsNo
                });
              }
            });
            params.taskGoodsMapperList = taskGoodsMapperList;
            // 编辑接口
            nowpagereq.edit(params).then(res => {
              if (res.code === 1) {
                this.$message.success("修改成功！");
                this.closeDialog();
                this.getTableDataList();
                this.resetState();
              } else {
                this.$message.error("修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            let params = JSON.parse(JSON.stringify(this.formData));
            let taskGoodsMapperList = [];
            this.checkedNos.forEach(el => {
              let item = this.productList.find(obj => obj.goodsName === el);
              if (item) {
                taskGoodsMapperList.push({
                  goodsName: item.goodsName,
                  goodsNo: item.goodsNo
                });
              }
            });
            params.taskGoodsMapperList = taskGoodsMapperList;
            if (!taskGoodsMapperList.length) {
              this.$message.error("请选择盘点产品");
              return;
            }
            // 新增接口
            nowpagereq.add(params).then(res => {
              if (res.code === 1) {
                this.$message.success("新增成功！");
                this.closeDialog();
                this.getTableDataList();
                this.resetState();
              } else {
                this.$message.error("新增失败！");
              }
            });
          }
        }
      });
    },
    openDialog(type) {
      this.dialogFormVisible = true;
      // eslint-disable-next-line eqeqeq
      this.dialogTitle = type == "add" ? "新增" : "编辑";
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.dialogTitle = null;
      this.nowChanceStau = "";
    }
  }
};
</script>

<style scoped lang="scss">
.df {
  display: flex;
  align-items: center;
  width: 100%;
}

.dfs {
  ::v-deep .el-form-item__content {
    flex-direction: column;
  }
  i {
    font-size: 30px;
    margin-left: 10px;
    cursor: pointer;
  }
}

.tags {
  width: 100%;
  display: flex;
  flex-wrap: wrap;

  .tag-item {
    height: 30px;
    padding: 5px 10px;
    background-color: #00a1c2;
    border-radius: 8px;
    display: flex;
    align-items: center;
    margin-top: 10px;
    margin-right: 10px;

    i {
      font-size: 14px;
    }
  }
}

.product-detail {
  .title {
    font-size: 16px;
    font-weight: bold;
  }
  .product-list {
    display: flex;
    flex-wrap: wrap;

    .product-item {
      background: #00a1c2;
      color: #fff;
      text-align: center;
      padding: 8px 24px;
      margin: 10px 20px 0 0;
      border-radius: 8px;
    }
  }
}
</style>
